package fileutil

import (
	"bufio"
	"log"
	"os"
	"strings"
)

// ReadLine 按行读取文件，直到文件结束，返回每一行的字符串
func ReadLine(filePath string) ([]string, error) {
	f, err := os.Open(filePath)
	if err != nil {
		log.Panicln(err)
		return nil, err
	}
	defer f.Close()
	resp := make([]string, 0, 16)
	sc := bufio.NewScanner(f)
	for sc.Scan() {
		lineStr := sc.Text()
		log.Printf("line=>[%v]\n", lineStr)
		resp = append(resp, lineStr)
	}
	return resp, nil
}

// ReadSeparatorLine 按行读取文件，并按照指定的分隔符切割行，直到文件结束，返回每一行被切割的字符串数组
func ReadSeparatorLine(filePath string, separator string) ([][]string, error) {
	f, err := os.Open(filePath)
	if err != nil {
		log.Panicln(err)
		return nil, err
	}
	defer f.Close()
	resp := make([][]string, 0, 16)
	sc := bufio.NewScanner(f)
	for sc.Scan() {
		lineStr := sc.Text()
		log.Printf("line=>[%v]\n", lineStr)
		resp = append(resp, strings.Split(lineStr, separator))
	}
	return resp, nil
}

// WriteSeparatorLine 按行追加写文件
func WriteSeparatorLine(filePath string, data [][]string, separator string) error {
	// 这里选择的是追加写，还可以定义覆盖写等
	f, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		log.Panicln(err)
		return err
	}
	defer f.Close()
	writer := bufio.NewWriter(f)
	bufioLen := 0
	for _, line := range data {
		lustre := strings.Join(line, separator)
		l, err := writer.WriteString(lustre + "\n")
		if err != nil {
			log.Panicf("writer.WriteString err:%v\n", err)
			return err
		}
		bufioLen += l
		if bufioLen > 1024*10 {
			err = writer.Flush()
			if err != nil {
				log.Panicf("writer.flush len:%v err:%v\n", bufioLen, err)
				return err
			}
		}
	}
	err = writer.Flush()
	if err != nil {
		log.Panicf("writer.flush err:%v\n", err)
		return err
	}
	return nil
}
